package com.lms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.lms.entity.Admin;
import com.lms.entity.Sms;
import com.lms.mapper.AdminMapper;
import com.lms.service.AdminService;
import com.lms.util.Md5Util;
import com.lms.util.RandomUtil;
import com.lms.vo.DataVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 管理员业务逻辑层接口实现类
 * @author: L-B-S
 * @Date: 2021/3/3 21:25
 * @modified_By:
 * @Version: 0.0$
 */
@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private Sms sms;

    @Override
    public DataVo<Admin> login(String username, String password) {
        // 1.通过用户名查询到用户对象
        Admin admin = adminMapper.selectByUserName(username);
        // 2.创建视图对象作为返回值
        DataVo<Admin> dataVo = new DataVo<>();
        // 3.if条件判断admin对象是否查询到，以及判定登录密码和查询到密码是否相同
        if (admin == null) {
            dataVo.setCode(1);
            dataVo.setMsg("用户不存在，请注册");
        } else if (!admin.isRole()) {
            dataVo.setCode(2);
            dataVo.setMsg("您没有登录权限，请联系管理员开通权限");
        } else if (!admin.getPassword().equals(Md5Util.stringMd5(password))) {
            dataVo.setCode(3);
            dataVo.setMsg("登录信息有误，请检查登录信息");
        } else {
            dataVo.setCode(0);
            dataVo.setMsg("登录成功，正在加载主页，请稍等...");
        }
        return dataVo;
    }

    @Override
    public DataVo<Admin> register(Admin admin) {
        DataVo<Admin> dataVo = new DataVo<>();
        Admin temp = adminMapper.selectByUserName(admin.getUserName());
        if (temp != null) {
            dataVo.setCode(1);
            dataVo.setMsg("该用户已注册，请重新输入注册信息");
        } else {
            admin.setPassword(Md5Util.stringMd5(admin.getPassword()));
            admin.setRole(true);
            adminMapper.insert(admin);
            dataVo.setCode(0);
            dataVo.setMsg("注册成功，正在跳转登录页面");
        }
        return dataVo;
    }

    @Override
    public DataVo<Admin> adminInfo(Admin admin, Integer page, Integer limit) {
        List<Admin> admins = new ArrayList<>();
        admins.add(admin);
        DataVo<Admin> dataVo = new DataVo<>();
        dataVo.setCode(0);
        dataVo.setMsg("");
        dataVo.setCount(1L);
        dataVo.setData(admins);
        return dataVo;
    }

    @Override
    public DataVo<Admin> sendMsg(Admin admin, HttpSession session) {
        DataVo<Admin> dataVo = new DataVo<>();
        Admin tempAdmin = adminMapper.selectByUserName(admin.getUserName());
        String str = RandomUtil.randomNumbers(6);
        String[] codeInfo = (String[]) session.getAttribute("codeInfo");
        codeInfo[2] = str;
        if (tempAdmin == null) {
            dataVo.setCode(2);
            dataVo.setMsg("改用户名不存在，请输入已注册的用户名");
        } else if (!tempAdmin.getPhone().equals(admin.getPhone())) {
            dataVo.setCode(1);
            dataVo.setMsg("用户名与手机号不匹配，请输入改用户名下的手机号");
        } else {
            try {
                String[] params = {str, String.valueOf(sms.getDuration())};
                SmsSingleSender sender = new SmsSingleSender(sms.getAppId(), sms.getAppKey());
                SmsSingleSenderResult result = sender.sendWithParam("86", admin.getPhone(), sms.getTemplateId(),
                        params, sms.getSmsSign(), "", "");
                System.out.println(result);
            } catch (IOException | HTTPException e) {
                e.printStackTrace();
            }
            dataVo.setCode(0);
            dataVo.setMsg("短信已发送成功，请注意查收");
        }
        return dataVo;
    }

    @Override
    public DataVo<Admin> verify(String code, HttpSession session) {
        DataVo<Admin> dataVo = new DataVo<>();
        String[] codeInfo = (String[]) session.getAttribute("codeInfo");
        if (codeInfo[2].equals(code)) {
            dataVo.setCode(0);
            dataVo.setMsg("验证成功，将跳转密码重置页面");
        } else {
            dataVo.setCode(1);
            dataVo.setMsg("验证码输入有误，请重新输入");
        }
        return dataVo;
    }

    @Override
    public DataVo<Admin> resetPwd(String password, HttpSession session) {
        DataVo<Admin> dataVo = new DataVo<>();
        String[] codeInfo = (String[]) session.getAttribute("codeInfo");
        Admin admin = adminMapper.selectByUserName(codeInfo[0]);
        if (admin.getPassword().equals(Md5Util.stringMd5(password))) {
            dataVo.setCode(1);
            dataVo.setMsg("当前输入密码为原密码，是否登录？");
        } else {
            admin.setPassword(Md5Util.stringMd5(password));
            adminMapper.updateById(admin);
            dataVo.setCode(0);
            dataVo.setMsg("重置密码成功，即将跳转登录界面，请稍等...");
        }
        session.removeAttribute("codeInfo");
        return dataVo;
    }

    @Override
    public int adminAuth(String secretKey) {
        if ("13579".equals(secretKey)) {
            return 0;
        }
        return 1;
    }

    @Override
    public DataVo<Admin> getList(Integer page, Integer limit) {
        DataVo<Admin> dataVo = new DataVo<>();
        dataVo.setCode(0);
        dataVo.setMsg("");

        IPage<Admin> adminPage = new Page<>(page, limit);
        IPage<Admin> result = adminMapper.selectPage(adminPage, null);

        dataVo.setData(result.getRecords());
        dataVo.setCount(result.getTotal());

        return dataVo;
    }

    @Override
    public DataVo<Admin> delAdmins(List<Admin> adminList) {
        DataVo<Admin> dataVo = new DataVo<>();
        List<Long> ids = new ArrayList<>();
        if (adminList.size() == 0) {
            dataVo.setCode(1);
            dataVo.setMsg("您还没有选择删除的行，请选择后操作");
        } else {

        }
        return null;
    }
}
